//
//  SquareDetailViewController.m
//  Findif
//
//  Created by Mac on 2019/2/11.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "SquareDetailViewController.h"
#import "SquareTableViewCell.h"
#import "SquareHeadrerView.h"
#import "NoCommitTableViewCell.h"
#import "SquareCommitModel.h"
#import "SquareCommitTableViewCell.h"
#import "MenuTableViewCell.h"
#import "GrayFooterView.h"
#import "PersonalViewController.h"
#import "GroupInfoViewController.h"
#import "GroupContractsViewController.h"
#import "ChatRoomViewController.h"
#import <JMessage/JMessage.h>
#import "MoreCommitViewController.h"
#import "MapViewController.h"

@interface SquareDetailViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,SquareTableViewCellDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, weak)UITextField * textField;
@property (nonatomic, weak)UIButton * sendButton;
@property (nonatomic, strong)NSArray <SquareCommitModel *> * listArray;
@property (nonatomic, copy)NSString * pid;
@property (nonatomic, weak)UIView * backView;
@property (nonatomic, weak)UITableView * menuView;
@property (nonatomic, strong)NSArray * titleArray;


@end

@implementation SquareDetailViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    self.title = self.model.user_name;
    self.pid = @"0";
    self.titleArray = @[@"关注",@"私聊",@"邀请",@"屏蔽",@"举报"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(commitSomePeoPle:) name:@"commitSomePeoPle" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToPerson:) name:@"pushToPerson" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PushToMoreCommit:) name:@"PushToMoreCommit" object:nil];
    
    [self setupUI];
}

- (void)loadData{
    
    [[ZRNetworkTool sharedTool] getDynamicCommentsWithID:self.model.id WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            self.listArray = [NSArray yy_modelArrayWithClass:[SquareCommitModel class] json:responseData[@"data"]];
        }
    }];
}


- (void)setListArray:(NSArray<SquareCommitModel *> *)listArray{
    
    _listArray = listArray;
    
    [self.tableView reloadData];
}

- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - kBarHeight - 65 * SCREENH6)];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
    //    tableView.rowHeight = 124 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[SquareTableViewCell class] forCellReuseIdentifier:@"SquareDetailTableViewCell"];
    [self.tableView registerClass:[NoCommitTableViewCell class] forCellReuseIdentifier:@"NoCommitTableViewCell"];
    [self.tableView registerClass:[SquareCommitTableViewCell class] forCellReuseIdentifier:@"SquareCommitTableViewCell"];
    [self.tableView registerClass:[SquareHeadrerView class] forHeaderFooterViewReuseIdentifier:@"SquareDatailHeadrerView"];
    
    [self.view addSubview:self.tableView];
    
    
    UIView * bottomView = [UIView new];
    
    bottomView.backgroundColor = ZRWhiteColor;
    bottomView.userInteractionEnabled = YES;
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
    
    
    UITextField * textFiled = [[UITextField alloc] init];
    
    textFiled.borderStyle = UITextBorderStyleRoundedRect;
    textFiled.backgroundColor = ColorWithRGB(0xE0E0E0);
    textFiled.returnKeyType = UIReturnKeyDone;
//    textFiled.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    textFiled.tintColor = ZRBlackColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x909090);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:14 * SCREENH6];
    textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"我来说两句~" attributes:attrs];
    textFiled.textColor = ZRBlackColor;
    textFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14 * SCREENH6];
    textFiled.delegate = self;
    
    self.textField = textFiled;
    
    [self.bottomView addSubview:self.textField];
    
    
    UIButton * sendButton = [UIButton new];
    
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(clickSendButton) forControlEvents:UIControlEventTouchUpInside];
    sendButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    sendButton.backgroundColor = ZRBlackColor;
    sendButton.layer.cornerRadius = 5 * SCREENH6;
    sendButton.layer.masksToBounds = YES;
    
    self.sendButton = sendButton;
    
    [self.bottomView addSubview:self.sendButton];
}

- (void)viewDidLayoutSubviews{
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(-kBarHeight);
        make.height.mas_equalTo(60 * SCREENH6);
        make.leading.trailing.mas_equalTo(self.view);
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.bottomView).offset(15 * SCREENH6);
        make.centerY.mas_equalTo(self.bottomView);
        make.width.mas_equalTo(295 * SCREENH6);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
    
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.bottomView).offset(-15 * SCREENH6);
        make.leading.mas_equalTo(self.textField.mas_trailing).offset(8 * SCREENH6);
        make.centerY.mas_equalTo(self.textField);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
      
        if (section == 0) {
            
            return 1;
        }else{
            
            if (self.listArray.count > 0) {
                
                return self.listArray.count;
            }else{
                
                return 1;
            }
            
        }
    }else{
        
        if (section == 0) {
            
            return self.titleArray.count;
        }else{
            
            return 1;
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
       
        if (indexPath.section == 0) {
            
            SquareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SquareDetailTableViewCell" forIndexPath:indexPath];
            
            cell.model = self.model;
            cell.delegate = self;
            
            return cell;
        }else{
            
            if (self.listArray.count > 0) {
                
                //                SquareCommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SquareCommitTableViewCell" forIndexPath:indexPath];
                
                SquareCommitTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
                if (cell == nil) {
                    cell = [[SquareCommitTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SquareCommitTableViewCell"];
                    
                }
                
                cell.model = self.listArray[indexPath.row];
                
                return cell;
            }else{
                
                NoCommitTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoCommitTableViewCell" forIndexPath:indexPath];
                
                return cell;
            }
            
        }
    }else{
        
        MenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DatailMenuTableViewCell" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            
            cell.showLabel.text = self.titleArray[indexPath.row];
        }else{
            
            cell.showLabel.text = @"取消";
        }
        
        
        return cell;
    }
    
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
        if (indexPath.section == 0) {
            // 使用缓存行高，避免计算多次
            return self.model.rowHeight;
        }else{
            
            if (self.listArray.count > 0) {
                
                SquareCommitModel * model = self.listArray[indexPath.row];
                
                return model.rowHeight;
            }else{
                
                return 80 * SCREENH6;
            }
            
        }
    }else{
        
        return 40 * SCREENH6;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if (section == 0) {
            
            return 43 * SCREENH6;
        }else{
            
            return 0;
        }
    }else{
        
        if (section == 0) {
            
            return 20 * SCREENH6;
        }else{
            
            return 0;
        }
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if (section == 0) {
            
            SquareHeadrerView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SquareDatailHeadrerView"];
            
            header.string = @"全部评论";
            return header;
        }else{
            
            return nil;
        }
    }else{
        
        if (section == 0) {
            
            GrayFooterView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"DatailGrayFooterView"];
            
            return header;
        }else{
            
            return nil;
        }
    }
    
}

- (void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF4F5F6);
        }
    }else{
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF0F0F0);
        }
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (tableView == self.tableView) {
//
//        SquareCommitModel * model = self.listArray[indexPath.row];
//        self.pid = [NSString stringWithFormat:@"%@",model.id];
//
//        [self.textField becomeFirstResponder];
//    }
    if(tableView == self.menuView){
       
        if (indexPath.section == 0) {
            
            [self removeMenuView];
            
            if (indexPath.row == 0) {
                //关注
                NSString * user_id = [NSString stringWithFormat:@"%@",self.model.user_id];
                [[ZRNetworkTool sharedTool] attentionUseroWithUser_id:user_id ResultWithBlock:^(BOOL success, id responseData) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }];
            }else if (indexPath.row == 1){
                //私聊
                NSString * user_id = DEF_GET_OBJECT(@"id");
                NSString * user_Str = [NSString stringWithFormat:@"%@",self.model.user_id];
                if ([user_id isEqualToString:user_Str]) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"亲，不能与自己私聊"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    NSString * phone = [NSString stringWithFormat:@"%@",self.model.phone];
                    
                    [JMSGConversation createSingleConversationWithUsername:phone completionHandler:^(id resultObject, NSError *error) {
                        
                        if (error == nil) {
                            HiddenBar;
                            ChatRoomViewController * roomVC = [ChatRoomViewController new];
                            
                            roomVC.conversation = resultObject;
                            
                            [self.navigationController pushViewController:roomVC animated:YES];
                        } else {
                            
                        }
                    }];
                }
            }else if (indexPath.row == 2){
                //邀请
                GroupContractsViewController * groupVC = [GroupContractsViewController new];
                
                [self.navigationController pushViewController:groupVC animated:YES];
                
                [groupVC returnGroupName:^(NSDictionary * _Nonnull localInfo) {
                    
                    if (localInfo[@"ID"]) {
                        
                        NSString * groupID = localInfo[@"ID"];
                        NSString * user_id = [NSString stringWithFormat:@"%@",self.model.user_id];
                        
                        NSDictionary * dict = @{@"inform_user_id":user_id,@"group_id":groupID};
                        
                        [[ZRNetworkTool sharedTool] invitationJoinGroupWithDict:dict WithBlock:^(BOOL success, id responseData) {
                            
                            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                           message:responseData[@"message"]
                                                                                    preferredStyle:UIAlertControllerStyleAlert];
                            
                            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                                  handler:^(UIAlertAction * action) {
                                                                                      
                                                                                  }];
                            
                            [alert addAction:defaultAction];
                            [self presentViewController:alert animated:YES completion:nil];
                        }];
                        
                    }
                }];
                
            }else if (indexPath.row == 3){
                //屏蔽
                NSString * user_id = [NSString stringWithFormat:@"%@",self.model.user_id];
                [[ZRNetworkTool sharedTool] shieldUserDynamicWithShield_user_id:user_id WithBlock:^(BOOL success, id responseData) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              [self loadData];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }];
                
            }else if (indexPath.row == 4){
                //举报
                NSString * ID = [NSString stringWithFormat:@"%@",self.model.id];
                NSDictionary * dict = @{@"dynamic_id":ID,@"report_cate_id":@"3"};
                
                [[ZRNetworkTool sharedTool] reportUserDynamicWithDict:dict WithBlock:^(BOOL success, id responseData) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:responseData[@"message"]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                              [self loadData];
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }];
            }
            
            
        }else{
            
            [self removeMenuView];
        }
    }  
}

- (void)commitSomePeoPle:(NSNotification *)noti{
    
    self.pid = noti.userInfo[@"ID"];
    NSString * user_name = noti.userInfo[@"user_name"];
    self.textField.placeholder = [NSString stringWithFormat:@"回复:%@",user_name];
    
    [self.textField becomeFirstResponder];
}


- (void)pushToPerson:(NSNotification *)noti{
    
    NSString * user_id = noti.userInfo[@"user_id"];
    
    HiddenBar;
    
    PersonalViewController * personVC = [PersonalViewController new];
    personVC.ID = user_id;
    
    [self.navigationController pushViewController:personVC animated:YES];
}

- (void)clickItemButton:(UIButton *)type WithCell:(SquareTableViewCell *)cell{
    
    [self didMenuButton];
}

- (void)clickLocalButtonLocal:(NSString *)local WithDynamic_latitude:(NSString *)latitude WithDynamic_longitude:(NSString *)longitude{
    
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = latitude;
    mapVC.merchants_longitude = longitude;
    mapVC.merchants_local = local;
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
    ShowBar;
}

- (void)clickGroupLabelWithCell:(SquareTableViewCell *)cell{
    
    NSDictionary * dict = @{@"id":cell.model.group_id};
    [[ZRNetworkTool sharedTool] checkGroupStatusWithDict:dict WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            HiddenBar;
            GroupInfoViewController * infoVC = [GroupInfoViewController new];
            
            infoVC.group_id = cell.model.group_id;
            
            [self.navigationController pushViewController:infoVC animated:YES];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
}

- (void)didMenuButton{
    
    UIView * backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    backView.backgroundColor = ZRBlackColor;
    backView.alpha = 0.4;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeMenuView)];
    backView.userInteractionEnabled = YES;
    [backView addGestureRecognizer:tapGR];
    
    self.backView = backView;
    
    [self.tabBarController.view addSubview:self.backView];
    
    
    UITableView * menuView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScreenH - kBarHeight - 260 * SCREENH6, kScreenW, 260 * SCREENH6)];
    
    menuView.delegate = self;
    menuView.dataSource = self;
    menuView.backgroundColor = ZRWhiteColor;
    menuView.separatorStyle = UITableViewCellSeparatorStyleNone;
    menuView.showsVerticalScrollIndicator = NO;
    
    self.menuView = menuView;
    
    [self.menuView registerClass:[MenuTableViewCell class] forCellReuseIdentifier:@"DatailMenuTableViewCell"];
    [self.tableView registerClass:[GrayFooterView class] forHeaderFooterViewReuseIdentifier:@"DatailGrayFooterView"];
    
    [self.tabBarController.view addSubview:self.menuView];
}

- (void)removeMenuView{
    
    [self.backView removeFromSuperview];
    [self.menuView removeFromSuperview];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
   
    self.textField.placeholder = @"我来说两句~";
    [self.textField resignFirstResponder];
    
    return YES;
}


- (void)clickSendButton{
    
    if (self.textField.text.length > 0) {
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        
        [dict setValue:self.model.id forKey:@"dynamic_id"];
        [dict setValue:self.textField.text forKey:@"content"];
        [dict setValue:self.pid forKey:@"pid"];
        
        [[ZRNetworkTool sharedTool] InitiateDynamicCommentWithDict:dict.copy WithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                [self.textField resignFirstResponder];
                self.textField.text = @"";
                self.textField.placeholder = @"我来说两句~";
                
                [self loadData];
                self.pid = @"0";
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
        
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"评论不能为空"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
    
}


- (void)PushToMoreCommit:(NSNotification *)noti{
    
    NSString * ID = noti.userInfo[@"ID"];
   
    HiddenBar;
    
    MoreCommitViewController * moreVC = [MoreCommitViewController new];
    
    moreVC.ID = ID;
    
    [self.navigationController pushViewController:moreVC animated:YES];
}


- (void)clickHeadImageViewWith:(NSString *)ID{
    
    HiddenBar;
    
    PersonalViewController * personVC = [PersonalViewController new];
    
    personVC.ID = ID;
    
    [self.navigationController pushViewController:personVC animated:YES];
    
    ShowBar;
}

@end
